#!/usr/bin/env python
# coding=utf-8
# @FileName  :main.py
# @Time      :2024/8/12 10:40
# @Author    :jdz
# @description :

import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware

from api.main import api_router
from config.env import AppConfig
from core import exception, middleware
from core.events import lifespan
from exception.base import CustomException

app = FastAPI(
    debug=AppConfig.app_debug,
    title=AppConfig.app_name,
    description=f"{AppConfig.app_name}接口文档",
    version=AppConfig.app_version,
    lifespan=lifespan,
    docs_url=AppConfig.app_docs_url,
    redoc_url=AppConfig.app_redoc_url,
)

# 解决跨域问题
app.add_middleware(middleware.ProcessTimeMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# 异常错误处理
app.add_exception_handler(CustomException, exception.custom_error_exp_handler)
app.add_exception_handler(RequestValidationError, exception.http422_error_handler)
app.add_exception_handler(HTTPException, exception.http_error_handler)
# 路由
app.include_router(api_router)
if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=AppConfig.app_host,
        port=AppConfig.app_port,
        reload=AppConfig.app_reload,
        workers=AppConfig.app_workers,
    )
